package visiopuce.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.jfree.io.IOUtils;

import visiopuce.ApplicationContexte;
import visiopuce.ICommandIds;
import visiopuce.objets.FeuillePuce;
import visiopuce.objets.Puce;
import visiopuce.service.AlterationServiceImpl;
import visiopuce.service.PersonneServiceImpl;
import visiopuce.service.PuceServiceImpl;
import visiopuce.ui.DossierEditorInput;
import visiopuce.ui.IdFeuillePuceDialog;
import visiopuce.ui.view.DossierEditor;

public class ImportDonneesFeuillePuceAction extends Action {
	private final IWorkbenchWindow window;

	public ImportDonneesFeuillePuceAction(String text, IWorkbenchWindow window) {

		super(text);
		this.window = window;
		// The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_IMPORT_FEUILLE_TRAVAIL);
		// Associate the action with a pre-defined command, to allow key
		// bindings.
		setActionDefinitionId(ICommandIds.CMD_IMPORT_FEUILLE_TRAVAIL);
		setText("Importer une feuille de travail");
		setImageDescriptor(visiopuce.Activator.getImageDescriptor("/icons/importerFeuille.png"));
	}

	public void run() {
		FeuillePuce fp = null;
		IdFeuillePuceDialog dialog = new IdFeuillePuceDialog(Display.getCurrent().getActiveShell());
		if (dialog.open() == IDialogConstants.OK_ID) {
			fp = dialog.getFeuillePuce();
			if (fp != null) {
				if (fp.getProtocole().contains("SurePrint")) {
					HashMap<String, Puce> puces = PuceServiceImpl.getInstance().getPuceFromFeuillePuce(fp.getIdFeuillePuce());
					if (puces != null) {
						try {
							DirectoryDialog dirDialog = new DirectoryDialog(Display.getCurrent().getActiveShell());
							dirDialog.setFilterPath(ApplicationContexte.REPERTOIRE_PUCE);
							String path = dirDialog.open();
							if (path != null) {
								path += "\\Samples\\";
								File repertoire = new File(path);
								String[] children = repertoire.list();
								for (String currentKey : puces.keySet()) {
									Puce puce = puces.get(currentKey);
									String numPrel = PuceServiceImpl.getInstance().getNumeroPrelevementByidPuce(puce.getIdPuce());
									String nomFeuille = "F" + fp.getIdFeuillePuce() + "_" + numPrel;
									for (String fileName : children) {
										if (fileName.contains(nomFeuille)) {
											String intervalBasedReport = repertoire + "\\" + fileName + "\\Reports\\IntervalBasedReport.xls";
											AlterationServiceImpl.getInstance().telechargerFichierSegment(puce, intervalBasedReport, false);
											String qcReport = repertoire + "\\" + fileName + "\\Reports\\QC Metrics Report.xls";
											AlterationServiceImpl.getInstance().telechargerFichierQC(puce, qcReport, numPrel);

											File repertoireFE = new File(repertoire + "\\" + fileName + "\\FE File\\");
											String[] childrenFE = repertoireFE.list();
											for (String fichierReport : childrenFE) {
												if (fichierReport.contains(".pdf")) {
													InputStream input;
													input = new FileInputStream(repertoireFE + "\\" + fichierReport);
													String repResultat = "";
													if (Character.isDigit(numPrel.charAt(1))) {
														repResultat = ApplicationContexte.REPERTOIRE_RESULTAT + "activité 20" + numPrel.substring(1, 3) + "\\" + numPrel.substring(0, 1) + "\\";
													} else {
														if (Character.isDigit(numPrel.charAt(2))) {
															repResultat = ApplicationContexte.REPERTOIRE_RESULTAT + "activité 20" + numPrel.substring(2, 4) + "\\" + numPrel.substring(0, 2) + "\\";
														}
													}
													OutputStream output = new FileOutputStream(repResultat + numPrel + "_QCFile.pdf");
													IOUtils.getInstance().copyStreams(input, output);
												}
											}
											IEditorInput editorInput = new DossierEditorInput(PersonneServiceImpl.getInstance().getIdPersonneFromObject(puce));
											PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(editorInput, DossierEditor.ID, true, IWorkbenchPage.MATCH_INPUT);
											IEditorPart editeurActif = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
											if (editeurActif instanceof DossierEditor) {
												DossierEditor editeur = (DossierEditor) editeurActif;
												if (editeur.getPuceTabItems().containsKey(puce.getIdPuce())) {
													editeur.getTabFolder().setSelection(editeur.getPuceTabItems().get(puce.getIdPuce()).getTabItem());
												} else {
													editeur.addPuceTabItem(puce);

												}
											}
										}
									}
								}
							}
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (PartInitException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			} else {
				MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Impossible", "Cette option ne fonctionne que pour les puces Agilent");
			}
		}

	}
}